import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import { Message } from '@arco-design/web-vue'
import { checkLoginUsingGet } from '@/api/authController'
import { useTeamStore } from '@/store'

const router = createRouter({
  history: createWebHistory(),
  routes
})
/**
 * 检查登录状态的守卫
 */
router.beforeEach(async (to, from, next) => {
  // 检查是否已登录
  const isAuthenticated = await checkLoginUsingGet()

  // 处理登录/注册页面的特殊逻辑
  if ((to.path === '/login' || to.path === '/register') && isAuthenticated) {
    Message.warning('请退出登录后操作')
    // 如果是从其他页面跳转来的，返回上一页
    if (from.path !== '/login' && from.path !== '/register') {
      return next(from.fullPath)
    }
    // 如果直接访问登录/注册页，跳转到首页
    return next('/')
  }

  // 检查路由是否允许游客访问
  const guestAccess = to.meta.guestAccess as boolean

  if (guestAccess) {
    // 游客可访问的路由，直接通过
    next()
  } else {
    // 其他需校验登录态
    if (isAuthenticated) {
      next()
    } else {
      Message.warning('请先登录')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  }
})

/**
 * 检查团队要求的守卫
 */
router.beforeEach((to, from, next) => {
  const teamStore = useTeamStore()
  const requireTeam = to.meta.requireTeam as boolean
  if (requireTeam && !teamStore.selectedTeam?.id) {
    Message.warning('请先选择或加入团队')
    next('/team/join')
  } else {
    next()
  }
})

router.afterEach((to) => {
  //自行实现页面标题和favicon设置 或者按照本标准meta.title/icon
  document.title = to.meta.title as string
  setFavicon(to.meta.icon as string)
})

function setFavicon(iconPath: string) {
  const link =
    (document.querySelector("link[rel*='icon']") as HTMLLinkElement) ||
    document.createElement('link')
  link.href = iconPath || '@/assets/logo.webp'
  document.getElementsByTagName('head')[0].appendChild(link)
}

export default router
